/*
 * Copyright (C) 2018 Zhengzhou grandtech Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.grandtech.com.
 * Developer Web Site: http://open.grandtech.com.
 */

package com.grandtech.oss.api;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.grandtech.oss.common.pojo.Pagination;
import com.grandtech.oss.common.pojo.RestfulMessage;
import com.grandtech.oss.exception.AssemblerException;
import com.grandtech.oss.exception.ErrorCable;
import com.grandtech.oss.exception.ErrorConstant;
import com.grandtech.oss.module.model.OSSAppInfo;
import com.grandtech.oss.service.OSSAppInfoService;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/***
 *
 * @since:oss-server 1.0
 * @author <a href="mailto:yanggh@foxmail.com">yanggh@foxmail.com</a> 
 * 2018/09/17 19:53
 */
@RestController
@RequestMapping("/api/v1/oss/app")
public class AppInfoApplication extends RootApis {
    /**
     * @apiDefine app app（应用管理）
     */

    @Autowired
    OSSAppInfoService ossAppInfoService;

    /***
     * @api {GET} /api/v1/oss/app/queryByPage queryByPage（获取应用列表）
     * @apiName queryByPage
     * @apiGroup app
     * @apiVersion 1.0.0
     *
     * @apiParam {Integer} page 当前页
     * @apiParam {Integer} rows 每页行数
     * @apiParam {String} sortOrder 排序字段
     * @apiParamExample {json} Request-Example：
     * {
     *     "rows": 10,
     *     "page": 1,
     *     "sortOrder": "asc"
     * }
     *
     * @apiSuccess {json} success 返回数据
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code": 8200,
     *     "count": 2,
     *     "current_page": 1,
     *     "message": null,
     *     "page_size": 10,
     *     "total_page": 1,
     *     "data":[{
     *         "code": "test",
     *         "createTime": "2018-09-10 17:18:27",
     *         "devId": "386607787ada4676a52cf78e1b15311a",
     *         "id:" "5234b8d4494b496fb8fcd218f85610b7",
     *         "intro": "",
     *         "name": "test",
     *         "useSpace": 8376085,
     *         "useSpaceStr": "7.99MB"
     *     }]
     * }
     */
    @ApiOperation(value = "获取应用列表", notes = "")
    @GetMapping("/queryByPage")
    public Pagination<OSSAppInfo> queryByPage(OSSAppInfo ossAppInfo,
                                              @RequestParam(value = "page", defaultValue = "1") Integer current_page,
                                              @RequestParam(value = "rows", defaultValue = "10") Integer page_size) {
        return ossAppInfoService.queryByPage(ossAppInfo, current_page, page_size);

    }

    /***
     * @api {POST} /api/v1/oss/app/queryById queryById（根据应用id查找应用）
     * @apiName queryById
     * @apiGroup app
     * @apiVersion 1.0.0
     *
     * @apiParam {String} id 应用id
     * @apiParamExample {json} Request-Example：
     * {
     *     "id": "5234b8d4494b496fb8fcd218f85610b7"
     * }
     *
     * @apiSuccess {json} success 返回数据
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code": 8200,
     *     "message": "Success"
     *     "data":{
     *         "code": "test",
     *         "createTime": "2018-09-10 17:18:27",
     *         "devId": "386607787ada4676a52cf78e1b15311a",
     *         "id": "5234b8d4494b496fb8fcd218f85610b7",
     *         "intro": "",
     *         "name": "test",
     *         "useSpace": 8376085,
     *         "useSpaceStr": "7.99MB"
     *     }
     * }
     */
    @PostMapping("/queryById")
    public RestfulMessage queryById(String id) {
        RestfulMessage restfulMessage = new RestfulMessage();
        try {
            assertArgumentNotEmpty(id, "项目id不能为空");
            restfulMessage.setData(ossAppInfoService.selectById(id));
            successResultCode(restfulMessage);
        } catch (Exception e) {
            restfulMessage = wrapperException(e);
        }
        return restfulMessage;
    }

    /***
     * @api {POST} /api/v1/oss/app/delete delete（根据应用id删除应用）
     * @apiName delete
     * @apiGroup app
     * @apiVersion 1.0.0
     *
     * @apiParam {String} id 应用id
     * @apiParamExample {json} Request-Example：
     * {
     *     "id": "5234b8d4494b496fb8fcd218f85610b7"
     * }
     *
     * @apiSuccess {json} success 返回数据
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code": 8200,
     *     "data": null,
     *     "message": "Success"
     * }
     */
    @PostMapping("/delete")
    public RestfulMessage delete(String id) {
        RestfulMessage restfulMessage = new RestfulMessage();
        try {
            //验证邮箱
            assertArgumentNotEmpty(id, "项目id不能为空");
            String[] ids = StrUtil.split(id, ",");
            ossAppInfoService.deleteBatchIds(Lists.newArrayList(ids));
            successResultCode(restfulMessage);
        } catch (Exception e) {
            restfulMessage = wrapperException(e);
        }
        return restfulMessage;
    }

    /***
     * @api {POST} /api/v1/oss/app/merge merge（新增或编辑应用）
     * @apiName merge
     * @apiGroup app
     * @apiVersion 1.0.0
     *
     * @apiParam {json} ossAppInfo 应用信息
     * @apiParamExample {json} Request-Example：
     * {
     *     "id": "5234b8d4494b496fb8fcd218f85610b7", --新增时为空，修改时非空
     *     "name": "meilc1",
     *     "code": "meilc2",
     *     "devId": "386607787ada4676a52cf78e1b15311a",
     *     "intro":"meilc12" --描述
     * }
     *
     * @apiSuccess {json} success 返回数据
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code": 8200,
     *     "data": null,
     *     "message": "Success"
     * }
     */
    @PostMapping("/merge")
    public RestfulMessage merge(OSSAppInfo ossAppInfo) {
        RestfulMessage restfulMessage = new RestfulMessage();
        try {
            //验证邮箱
            assertArgumentNotEmpty(ossAppInfo.getName(), "项目名称不能为空");
            assertArgumentNotEmpty(ossAppInfo.getCode(), "项目code不能为空");
            assertArgumentNotEmpty(ossAppInfo.getDevId(), "开发者不能为空");
            String regex = "^.*?(\\\\|\\/|\\:|\\*|\\?|\\？|\\\"|\\“|\\”|\\>|\\<|\\|).*";
            if (ReUtil.isMatch(regex, ossAppInfo.getCode())) {
                throw new AssemblerException(new ErrorCable(ErrorConstant.REQUEST_PARAMS_NOT_VALID, "项目code不能包含以下字符: / /: *?<>|"));
            }
            //不能包含\s字符
            //不能包含中文
            regex = ".*?[\\u4e00-\\u9fa5\\s].*";
            if (ReUtil.isMatch(regex, ossAppInfo.getCode())) {
                throw new AssemblerException(new ErrorCable(ErrorConstant.REQUEST_PARAMS_NOT_VALID, "项目code不能包含中文"));
            }
            //判断是否存在
            if (ossAppInfoService.queryByCode(ossAppInfo.getCode()) > 0) {
                throw new AssemblerException(new ErrorCable(ErrorConstant.REQUEST_PARAMS_NOT_VALID, "项目code已经存在"));
            }
            if (StrUtil.isEmpty(ossAppInfo.getId())) {
                //insert
                ossAppInfo.setCreateTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
                ossAppInfo.setUseSpace(0L);
                ossAppInfo.setUseSpaceStr("0kb");
                ossAppInfoService.insert(ossAppInfo);
            } else {
                ossAppInfoService.updateById(ossAppInfo);
            }
            successResultCode(restfulMessage);
        } catch (Exception e) {
            restfulMessage = wrapperException(e);
        }
        return restfulMessage;
    }

}
